package cvsexercise12;

/* import required for Random class */
import java.util.*;

public class CustomExceptionHandling {

	
	/* Constant total value */
	public static final int NUM_PLANETS = 8;
	
	/* Create an enumeration type (Planets) that contains the following constants:
	 * MECURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE 
	 */
	public enum Planets {
		MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE
	}


	/* Create a method called triggerException() that takes a Planets parameter as input
	 * and throws a MyCustomException if the input parameter equals Planets.MARS
	 * NOTE: the throw keyword should be used in conjunction with a new instance of the
	 *       custom exception class in order to generate the exception
	 * NOTE: when throwing the exception, pass a String to the constructor of the 
	 *       MyCustomException class
	 */
	public static void triggerException(Planets currentPlanet) throws MyCustomException {
	
		if (currentPlanet == Planets.MARS) {
			throw new MyCustomException("MARS ATTACKS! MyCustomException Triggered!");
		} else {
			System.out.println("The current planet is " + currentPlanet.toString());
		}
	}

	/* main method should handle the NullPointerException thrown by methodD() */
	public static void main(String[] args) {
		
		/* Output a start message to the console */
		System.out.println("Exercise 12 - Custom Exception Handling started");
		
		System.out.println("Enter main method");
		
		/* local variable to store Planets selection from random generator */
		Planets myPlanet = null;
		
		/* Generate a random integer between 0 and NUM_PLANETS */
		Random randomGenerator = new Random();
		for (int idx = 0; idx < 25; idx++) {
			int randomInt = randomGenerator.nextInt(NUM_PLANETS);
			
			/* Determine which planet to use */
			switch(randomInt) {
			case 0:
				myPlanet = Planets.MERCURY;
				break;
			case 1:
				myPlanet = Planets.VENUS;
				break;
			case 2:
				myPlanet = Planets.EARTH;
				break;
			case 3:
				myPlanet = Planets.MARS;
				break;
			case 4:
				myPlanet = Planets.JUPITER;
				break;
			case 5:
				myPlanet = Planets.SATURN;
				break;
			case 6:
				myPlanet = Planets.URANUS;
				break;
			case 7:
				myPlanet = Planets.NEPTUNE;
				break;
			default:
				break;
			}
			
			/* Use a try-catch-finally to handle the exception (MyCustomException) */
			try {
				System.out.println("main method: iteration[" + (idx+1) + "]: enter try block");
				triggerException(myPlanet);
				System.out.println("main method: iteration[" + (idx+1) + "]: exit try block");
			} catch (MyCustomException ex) {
				System.out.println("main method: iteration[" + (idx+1) + "]: enter catch block");
				ex.printStackTrace();
				System.out.println("main method: iteration[" + (idx+1) + "]: exit catch block");
			}
		}
	

		System.out.println("Exit main method");
		
		/* Output a completed message to the console */
		System.out.println("Exercise 12 - Custom Exception Handling completed");
	}
}
